package com.mz.service.sys;

import java.text.SimpleDateFormat;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import com.mz.base.util.ATTSystem;
import com.mz.base.util.DBUtil;
import com.mz.base.util.MD0Util;
import com.mz.base.util.Page;
import com.mz.entity.SysUsers;
import com.mz.service.CommonService;

public class SysUsersService {
	
	/**
	 * 查询系统管理员列表
	 * @param page
	 * @param sysUsers
	 */
	public void findSysUsers(Page page, SysUsers sysUsers){
		DBUtil db = new DBUtil();
		String sql = "select a.*, b.roleName from sys_users a, sys_role b where a.roleId=b.roleId and a.status<>"+ATTSystem.MARK_DELETE;
		if(sysUsers!=null){
			String where = CommonService.objectToWhere(sysUsers, "a");
			if(!StringUtils.isEmpty(where)){
				sql += " and " + where;
			}
		}
		db.search(page, sql);
	}
	/**
	 * 保存管理员信息
	 * @param sysUsers
	 * @return
	 */
	public int saveSysUsers(SysUsers sysUsers){
		DBUtil db = new DBUtil();
		int rows = 0;
		if(sysUsers.getUserId()!=null){
			String sql = "update sys_users set realName='" + sysUsers.getRealName()+"', " +
											  "password='" + MD0Util.encryptionMD0ofStr(sysUsers.getPassword())+"', " +
											  "roleId=" + sysUsers.getRoleId() + ", " +
											  "status=" + sysUsers.getStatus() + ", " +
											  "mobile='" + sysUsers.getMobile() + "', " +
											  "email='" + sysUsers.getEmail() + "', " +
											  "updateTime=now(), " +
											  "updateUser=" + sysUsers.getUpdateUser() + 
						 " where userId="+sysUsers.getUserId();
			rows = db.update(sql);
		}else{
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String[] fields = new String[]{"userName", "password", "realName", "status", "roleId",
					"email", "mobile", "createTime", "createUser", "updateTime", "updateUser"};
			Object[] values = new Object[]{sysUsers.getUserName(), MD0Util.encryptionMD0ofStr(sysUsers.getPassword()),
					sysUsers.getRealName(), sysUsers.getStatus(), sysUsers.getRoleId(), sysUsers.getEmail(),
					sysUsers.getMobile(), format.format(sysUsers.getCreateTime()), sysUsers.getCreateUser(),
					format.format(sysUsers.getUpdateTime()), sysUsers.getUpdateUser()};
			rows = db.insert("sys_users", fields, values);
		}
		return rows;
	}
	/**
	 * 获取管理员信息
	 * @param userId
	 * @return
	 */
	public JSONObject getSysUsersById(Long userId){
		DBUtil db = new DBUtil();
		String sql = "select * from sys_users where userId="+userId;
		return db.selectToJson(sql);
	}
	/**
	 * 删除管理员账号
	 * @param userId
	 * @param sessionUserId
	 * @return
	 */
	public int deleteSysUsers(Long userId, Long sessionUserId){
		DBUtil db = new DBUtil();
		String sql = "update sys_users set status=-1, updateTime=now(), updateUser="+sessionUserId+" where userId="+userId;
		return db.update(sql);
	}
}